package com.blog.controller.admin;

import com.blog.controller.BackendController;
import com.blog.model.User;
import com.blog.service.UserService;
import com.blog.utils.JsonResult;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.mapper.entity.Example;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/admin/user")
public class UserController extends BackendController {

    @Resource
    private UserService userService;
//    @RequestMapping("")
//    public String  index(HttpServletRequest request){
//        List<User> data = userService.findAll();
//        request.setAttribute("data",data);
//        return "admin/user/index";
//    }

    @RequestMapping("")
    public ModelAndView getAll(User user) {
        ModelAndView result = new ModelAndView("/admin/user/index");
//        List<User> data = userService.findAll();
//        Example example = new Example(User.class);
//        Example.Criteria criteria = example.createCriteria();

        List<User> userList = userService.getAll(user);
        result.addObject("pageInfo", new PageInfo<User>(userList));
        result.addObject("queryParam", user);
        result.addObject("page", user.getPage());
        result.addObject("rows", user.getRows());
        return result;
    }

    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable Integer id,HttpServletRequest request){
        User data = userService.getUser(id);
        request.setAttribute("info",data);
        return "admin/user/edit";
    }

    @RequestMapping(value = "/editsave",method = RequestMethod.POST)
    public String editsave(User user){
        userService.editUser(user);
        return "redirect:/admin/user";
    }

    @RequestMapping("/add")
    public String add(){
        return "/admin/user/add";
    }

    @RequestMapping("/postadd")
    public String postadd(User user){
        userService.add(user);
        return "redirect:/admin/user";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult del(@Param("id") Integer id){
        try {
            userService.delete(id);
            return JsonResult.ok();
        }catch (Exception e){
            return JsonResult.fail(e.getMessage());
        }
    }

    @RequestMapping("/editor")
    public String editor(){
        return "admin/user/editor";
    }
}
